// KOA 暂时不能更改，可能会导致页面无法正常加载
// "koa": "^2.0.0",
// "koa-bodyparser": "^3.2.0",
// "koa-qs": "^2.0.0",
// "koa-router": "^7.0.1",
// "koa-static": "^3.0.0",
// "koa-webpack-middleware": "1.0.1",

require('babel-polyfill');

const fs         = require('fs');
const path       = require('path');
const Koa        = require('koa');
const server     = require('koa-static');
const Router     = require('koa-router');
const qs         = require('koa-qs');
const bodyParser = require('koa-bodyparser');

const staticPath = path.resolve(__dirname, '../temp');

const app = new Koa();
app.proxy = true;

app.use(server(staticPath));

qs(app, 'first');
app.use(bodyParser());

app.use((ctx, next) => {
  // 过滤 webpack-dev-server
  if (!ctx.url.startsWith('/sockjs-node/info')) {
    const start = new Date;
    return next().then(() => {
      const ms = new Date - start;
      ctx.set('X-Response-Time', `${ms}ms`);
      console.log(`${ctx.method} ${ctx.status} ${ctx.url} - ${ms}ms`);
    });
  }
});

const webpack           = require('webpack');
const webpackMiddleware = require('koa-webpack-middleware');
const webpackConfig     = require('../webpack/webpack.server.js');
const compile           = webpack(webpackConfig);


app.use(webpackMiddleware.devMiddleware(compile, webpackConfig.devServer));
app.use(webpackMiddleware.hotMiddleware(compile, {
  // log: console.log,
  // path: '/__webpack_hmr',
  // heartbeat: 10 * 1000,
}));

const backRouter = new Router({
  prefix: '',
});
require('./backRouter')(backRouter, app);
app
  .use(backRouter.routes())
  .use(backRouter.allowedMethods());


app.use((ctx, next) => {

  next();

  if (404 !== ctx.status) {
    return;
  }


  // we need to explicitly set 404 here
  // so that koa doesn't assign 200 on body=
  ctx.status = 404;
  if (ctx.is('application/json')) {
    ctx.body = {
      error_code: 404,
      message: 'Not Found !',
      data: {},
    };
  } else {

    // redirect 方法会重置浏览器端 url
    // 注意: 开发模式下会被 koa-webpack-middleware 中间件拦截
    //ctx.redirect('/');
    //ctx.body = '404 的重大问题';
  }
});


app.listen(3000, '0.0.0.0', (err, result) => {
  if (err) {
    return console.error(err);
  }

  console.log(`Listening at http://0.0.0.0:3000/`);
});
